﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Json;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.Web.Http;

namespace BackgroundTasks
{
    public sealed class TileUpdater : IBackgroundTask
    {
        static int totalItems = 3;
        
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Get a deferral, to prevent the task from closing prematurely 
            // while asynchronous code is still running.
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            // Download the feed.
            var feed = await GetTileData();

            // Update the live tile with the feed items.
            UpdateTile(feed);

            // Inform the system that the task is finished.
            deferral.Complete();
        }

        private static async Task<JsonArray> GetTileData()
        {
            JsonArray feed = null;

            try
            {
                HttpClient client = new HttpClient();
                Uri uri = new Uri("http://www.atletikasvk.sk/DataOutput/Articles");
                string jsonText = await client.GetStringAsync(uri);
                feed = JsonArray.Parse(jsonText);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return feed;
        }

        private static void UpdateTile(JsonArray feed)
        {
            // Create a tile update manager for the specified syndication feed.
            var updater = TileUpdateManager.CreateTileUpdaterForApplication();
            updater.EnableNotificationQueue(true);
            updater.Clear();

            // Keep track of the number feed items that get tile notifications. 
            int itemCount = 0;
            string[] imagePaths = new string[] { "Assets/Tiles/Toth.png", "Assets/Tiles/Veldakova.png", "Assets/Tiles/Lomnicky.png" };
            
            foreach (JsonValue groupValue in feed)
            {
                JsonObject jsonArticle = groupValue.GetObject();

                XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150PeekImage03);

                // Set text
                string titleText = feed == null ? String.Empty : jsonArticle["Title"].GetString();
                XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");
                tileTextAttributes[0].InnerText = titleText;

                // Set branding
                var sqTileBinding = (XmlElement)tileXml.GetElementsByTagName("binding").Item(0);
                sqTileBinding.SetAttribute("branding", "none");

                // Set image
                var wideTileImage = (XmlElement)tileXml.GetElementsByTagName("image").Item(0);
                wideTileImage.SetAttribute("src", imagePaths[itemCount]);

                // Create a new tile notification. 
                updater.Update(new TileNotification(tileXml));

                // Don't create more than N notifications.
                if (itemCount++ > totalItems) break;
            }

        }

        
    }
}
